<template>
    <div class="watch-person">
    <h1>通过watch监视 ref 定义的基本数据类型</h1>
        <h2> 当前求和为： {{ sum }}</h2>
        <button @click="add">求和</button>
    <h1>通过watch监视 ref 定义的对象</h1>
    <h2> 姓名： {{ person.name }}</h2>
    <h2> 年龄： {{ person.age }}</h2>
    <button @click="changeName">修改名字</button>
    <button @click="changeAge">修改年龄</button>
    <button @click="changePerson">修改Person</button>

    <h1>通过watch监视 reactive 定义的对象</h1>
    </div>
</template>

<script setup lang="ts" name="PersonRef">
    //  用来创建响应式的函数， 用于创建一个响应式的引用对象，通常用来包装基本类型（如数字、字符串、布尔值等），使其具有响应性
    import { ref, watch, watchEffect } from 'vue';

    let sum =ref(0);
    function add() {
        sum.value = sum.value + 1;
    }

    const stopWatch = watch(sum, (newValue, oldValue) => {
        console.log(`sum changed from ${oldValue} to ${newValue}`);
        // 但值大于10的时候停止watch
        if (newValue > 10) {
            stopWatch();
        }
    });

    let person = ref({
       name: '张三',
       sex: '男',
       age: 0,
       address: {
           city: '北京',
           street: '北京街道'
       }
    });
    
    function changeName() {
        person.value.name = '李四';
    }
    function changeAge() {
        person.value.age = person.value.age + 1;
    }

    function changePerson() {

        person.value.age += 1
        person.value = {
            name: '王五',
            sex: '女',
            age: person.value.age,
            address: {
                city: '上海',
                street: '上海街道'
            }
            
        };
    }

    watch(person, (newValue, oldValue) => {
        console.log(`person changed from `, oldValue, newValue);
    },
    //  如果不添加deep 那么只有对象地址被修改的时候才会被监视
    {
        deep: true
    });

    watch(() => person.value.name, (newValue, oldValue) => {
        console.log(`person changed from `, oldValue, newValue);
    })

    watch([() => person.value.address.city, () => person.value.address.street], (newValue, oldValue) => {
        console.log(`person changed from `, oldValue, newValue);
    })

    watchEffect(()=>{

        console.log(`@ `, person.value);
    })


</script>

<style scoped>
h1 {
    color: #42b983;
    font-family: Arial, sans-serif;
    text-align: center;
    margin: 20px;
}
button {
    margin-top: 10px;
    padding: 5px 10px;
    background-color: #42b983;
    color: white;
    border: none;
    border-radius: 5px;
    cursor: pointer;
}
button:hover {
    background-color: #369870;
}
</style>